<?php
/**
 * Created by PhpStorm.
 * User: 123
 * Date: 2020/7/2
 * Time: 10:45.
 */

namespace app\admin\controller;

use app\reuse\controller\ResponseJson;
use app\service\IndustryService;
use app\service\RankingService;
use app\service\ResourceService;
use Redis\Redis;
use think\Db;
use think\facade\Request;

/**
 * 行业管理.
 *
 * @author   juzi
 * @blog     https://blog.csdn.net/juziaixiao
 *
 * @version  1.0.0
 * @datetime 2020年7月2日10:49:18
 */
class Industry extends Common
{
    use ResponseJson;

    /**
     * 构造方法.
     *
     * @author   juzi
     * @blog     https://blog.csdn.net/juziaixiao
     *
     * @version  1.0.0
     * @datetime 2020年6月24日13:23:09
     */
    public function __construct()
    {
        // 调用父类前置方法
        parent::__construct();


    }

    /**
     * [Index 行业列表].
     *
     * @author   juzi
     * @blog     https://blog.csdn.net/juziaixiao
     *
     * @version  1.0.0
     * @datetime 2020年6月24日13:23:09
     */
    public function Index()
    {
        if ('ajax' != input('get.action')) {
            return $this->fetch();
        } else {
            // 参数
            $params = input();

            // 条件
            $where = IndustryService::IndustryListWhere($params);
            // dump($where);exit;
            // 获取总数
            $total = IndustryService::IndustryTotal($where);

            $data_params = [
                'where' => $where,
                'page' => true,
                'field' => 'id,title,level,max_worth,min_worth,status,category',
                'number' => 20,
                'total_num' => true,
            ];
            $info = IndustryService::IndustryList($data_params);


            return ['code' => 0, 'msg' => '', 'count' => $total, 'data' => $info['data']];
        }
    }

    /**
     * [Saveinfo 行业编辑页面].
     *
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     *
     * @version 1.0.0
     * @date    2020年7月5日20:17:08
     */
    public function Saveinfo()
    {

        //$industry_level_arr=Db::name('industry_level')->where('id > 0')->field('title,id')->select();
        $industry_level_arr = [];
        for ($i = 0; $i < 12; ++$i) {
            $industry_level_arr[$i]['id'] = $i + 1;
            $industry_level_arr[$i]['title'] = ($i + 1) . "级";
        }
        $this->assign('industry_level_arr', $industry_level_arr);
        // 参数
        $params = input();

        // 数据
        $data = [];
        if (!empty($params['id'])) {
            // 获取列表
            $data_params = [
                'm' => 0,
                'n' => 1,
                'page' => false,
                'where' => ['id' => intval($params['id'])],
                'field' => '*',
            ];
            $ret = IndustryService::IndustryList($data_params);
            $data = empty($ret['data'][0]) ? [] : $ret['data'][0];
        }
        //dump($data);exit;
        $this->assign('res', $data);

        return $this->fetch();
    }

    /**
     * [Save 行业添加/编辑].
     *
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     *
     * @version 1.0.0
     * @date    2020年6月23日09:57:30
     */
    public function Save()
    {
        // 是否ajax
        if (!IS_AJAX) {
            return $this->error('非法访问');
        }

        // 开始操作
        $params = $this->data_post;

        //数据校验
        IndustryService::VaryData($params);
        //整理数据
        $data = IndustryService::HandleData($params);
        IndustryService::SaveInd($data, $params);
        # 更新redis
        $this->changeRedis($params['id']);
        //dump($data);exit;
        return json(DataReturn('保存成功', 0));
    }

    function changeRedis($id)
    {
        $redis = new Redis();
        $info = Db::table('industry i')
            ->field('i.id,title,logo,min_worth,max_worth,i.desc,detail,
                (select min(day_income) from industry_cycleincome where industry_id=i.id) min_ratio,
                (select max(day_income) from industry_cycleincome where industry_id=i.id) max_ratio
                ')
            ->where("i.is_del=2 and i.category=1 and i.status=1")
            ->order('i.level asc')
            ->select();
        # 存入redis
        $redis->hSetJson('industryInfo', 'list', $info);
        if (!empty($id)) {
            $detail = Db::table('industry i')
                ->field('i.id,i.title,logo,min_worth,max_worth,i.level,i.desc,detail,ml.title levelTitle,i.day_rent,
                (select min(day_income) from industry_cycleincome where industry_id=i.id) min_ratio,
                (select max(day_income) from industry_cycleincome where industry_id=i.id) max_ratio,
                (select min(cycle_period) from industry_cycleincome where industry_id=i.id) min_period,
                (select max(cycle_period) from industry_cycleincome where industry_id=i.id) max_period
                ')
                ->leftJoin('member_level ml','ml.level=i.level')
                ->where(array('i.id' => $id))
                ->find();
            $cycleIncome = Db::table('industry_cycleincome')->where(array('industry_id' => $id))->select();
            $detail['detail'] = ResourceService::ContentStaticReplace($detail['detail']);
            $info = array('info' => $detail, 'cycleIncome' => $cycleIncome);
            $redis->hSetJson('industryDetail', strval($id), $info);
        }
    }

    /**
     * [删除行业].
     *
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     *
     * @version 1.0.0
     * @date    2020年6月23日09:57:30
     */
    public function DelInfo()
    {
        // 是否ajax
        if (!IS_AJAX) {
            return $this->error('非法访问');
        }
        //判断行业是否占用中
        $id = input('post.id');
        $id = explode(',', $id);
        $where_busines = [
            ['industry_id', 'in', $id],
            ['status', '<>', 5],
        ];
        $member_business = Db::name('member_business')->where($where_busines)->count();
        if ($member_business > 0) {
            return json(DataReturn('行业正在占用中', '30009'));
        }


        $where_del = [['id', 'in', $id]];
        $sql = Db::name('industry')->where($where_del);
        $cates = $sql->field('category')->select();
        foreach ($cates as $v) {
            if ($v['category'] != 1) {
                return json(DataReturn('默认行业无法删除', '30011'));
            }
        }

        Db::startTrans();
        $re = Db::name('industry')->where($where_del)->update(['is_del' => 1]);
        if (!$re) {
            Db::rollback();
            return json(DataReturn('删除行业失败', '30010'));
        }
        Db::commit();
        return json(DataReturn('删除成功', 0));
    }

    /**
     * [行业级别设置列表].
     *
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     *
     * @version 1.0.0
     * @date    2020年7月5日20:18:20
     */
    public function Levels()
    {
        if ('ajax' != input('get.action')) {
            return $this->fetch();
        } else {
            // 参数
            $params = input();

            // 条件
            $where = IndustryService::LevelsListWhere($params);
            // dump($where);exit;
            // 获取总数
            $total = IndustryService::LevelsTotal($where);

            $data_params = [
                'where' => $where,
                'page' => true,
                'field' => '*',
                'number' => 12,
                'total_num' => true,
            ];
            $info = IndustryService::LevelsList($data_params);

            //dump($info['data']);exit;
            return ['code' => 0, 'msg' => '', 'count' => $total, 'data' => $info['data']];
        }
    }

    /**
     * [Savelevels 升级设置页面].
     *
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     *
     * @version 1.0.0
     * @date    2020年7月5日20:17:08
     */
    public function Savelevels()
    {
        $industry_level_arr = [];
        for ($i = 0; $i < 12; ++$i) {
            $industry_level_arr[$i]['id'] = $i + 1;
            $industry_level_arr[$i]['title'] = ($i + 1) . "级";
        }
        $this->assign('industry_level_arr', $industry_level_arr);
        // 参数
        $params = input();

        // 数据
        $data = [];
        if (!empty($params['id'])) {
            // 获取列表
            $data_params = [
                'm' => 0,
                'n' => 1,
                'page' => false,
                'where' => ['id' => intval($params['id'])],
                'field' => '*',
            ];
            $ret = IndustryService::LevelsList($data_params);
            $data = empty($ret['data'][0]) ? [] : $ret['data'][0];
            $levels = Db::name('industry_level_limits')->where('level_id=' . $data['id'])->select();
            $data['levels'] = $levels;
//            dump($data);exit;
        }

        $this->assign('res', $data);

        return $this->fetch();
    }

    /**
     * [Save 升级设置].
     *
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     *
     * @version 1.0.0
     * @date    2020年7月5日20:17:08
     */
    public function Savele()
    {
        // 是否ajax
        if (!IS_AJAX) {
            return $this->error('非法访问');
        }
        // 开始操作
        $params = $this->data_post;


        IndustryService::SaveLe($params);
        $this->changeLevelRedis();

        return json(DataReturn('保存成功', 0));
    }

    function changeLevelRedis()
    {
        $info = Db::table('member_level')->select();
        if (!empty($info)) {
            $redis = new Redis();
            foreach ($info as $k => $v) {
                $redis->hSetJson('memberLevelInfo', strval($v['level']), $info[$k]);
            }
        }
    }
}
